import { defineStore } from 'pinia'
import { mapToJson, jsonToMap } from '@/util/util.js'

const PersistentList = [
    'bookmarkMap',
    'automaticBookMark',
]

// 你可以任意命名 `defineStore()` 的返回值，但最好使用 store 的名字，同时以 `use` 开头且以 `Store` 结尾。
// (比如 `useUserStore`，`useCartStore`，`useProductStore`)
// 第一个参数是你的应用中 Store 的唯一 ID。
// -项目基础仓库
export const useNWStore = defineStore('novelWatcherStore', {
    state: () => ({
        count: 0,
        novel: null,
        book: null,
        rendition: null,
        bookmarkMap: new Map(),
        prop: {
            nid: 1,
            chapterName: '章节名称',
        },
        automaticBookMark: true,
        Auto_Bookmark_Name: '最后一次阅读位置'
    }),
    getters: {

    },
    actions: {
        increment() {
            this.count++
        },
        loadPersistedData() {
            try {
                let json;
                if (this.prop.nid === 'local')
                    json = localStorage.getItem('nwStore-' + this.prop.nid + "-" + this.prop.chapterName)
                else
                    json = localStorage.getItem('nwStore-' + this.prop.nid)
                if (!json) return;
                const dataMap = jsonToMap(json)
                for (let i = 0; i < PersistentList.length; i++) {
                    const key = PersistentList[i];
                    const value = dataMap.get(key);
                    if (value !== undefined) {
                        this[key] = value
                    }
                }
            } catch (error) {
                console.error('Error loading persisted data:', error)
            }
        },
        savePersistedData() {
            try {
                const dataMap = new Map();
                for (let i = 0; i < PersistentList.length; i++) {
                    const key = PersistentList[i];
                    const value = this[key];
                    // console.log(key + " = " + value);
                    dataMap.set(key, value)
                }
                if (this.prop.nid === 'local')
                    localStorage.setItem('nwStore-' + this.prop.nid + "-" + this.prop.chapterName, mapToJson(dataMap))
                else
                    localStorage.setItem('nwStore-' + this.prop.nid, mapToJson(dataMap))
            } catch (error) {
                console.error('Error saving persisted data:', error)
            }
        },
    }
})